package com.holike.crm.dialog;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gallopmark.recycler.adapterhelper.CommonAdapter;
import com.holike.crm.R;
import com.holike.crm.base.MyApplication;
import com.holike.crm.bean.UpdateBean;
import com.holike.crm.util.AppUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.util.List;

/**
 * 版本更新提示框（强制更新，弹窗后不能点返回键取消，下载完成更新调起系统安装app并退出app）
 */
public class UpdateAppDialog extends CommonDialog {
    //    private OnUpdateButtonClickListener updateButtonClickListener;
    private OnUpdateListener mListener;
    private TextView mUpdateTextView;
    private ProgressBar mProgressbar;

    public UpdateAppDialog(@NonNull Context context, UpdateBean updateBean, OnUpdateListener listener) {
        super(context, R.style.Dialog);
        this.mListener = listener;
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        setup(updateBean);
    }

//    public UpdateAppDialog setUpdateButtonClickListener(OnUpdateButtonClickListener updateButtonClickListener) {
//        this.updateButtonClickListener = updateButtonClickListener;
//        return this;
//    }

    @Override
    protected int bindContentView() {
        return R.layout.dialog_update_app;
    }

    private void setup(UpdateBean updateBean) {
        TextView tvCurrentVersion = mContentView.findViewById(R.id.tv_current_version);
        String currentVersion = mContext.getString(R.string.tips_current_version) + AppUtils.getVersionName(true);
        tvCurrentVersion.setText(currentVersion);
        TextView tvNewestVersion = mContentView.findViewById(R.id.tv_newest_version);
        RecyclerView recyclerView = mContentView.findViewById(R.id.rv_message);
        mProgressbar = mContentView.findViewById(R.id.progressbar);
        mUpdateTextView = mContentView.findViewById(R.id.tv_update_now);
        if (updateBean.getDetailArray() != null && !updateBean.getDetailArray().isEmpty()) {
            TipsAdapter adapter = new TipsAdapter(getContext(), updateBean.getDetailArray());
            recyclerView.setAdapter(adapter);
        }
        String source = mContext.getString(R.string.dialog_update_version);
        if (!TextUtils.isEmpty(updateBean.getActualversion())) {
            source += updateBean.getActualversion();
        }
        tvNewestVersion.setText(source);
        mUpdateTextView.setOnClickListener(view -> startDownload(updateBean.getUpdatepath()));
    }

    private void startDownload(String url) {
        String apkPath = AppUtils.getTargetApkPath();
        if (!TextUtils.isEmpty(apkPath) && new File(apkPath).exists()) {  //下载记录已存在
            checkAndInstall(apkPath);
            mUpdateTextView.setEnabled(true);
        } else {
            mUpdateTextView.setEnabled(false);
            FileDownloader.getImpl().create(url).setPath(apkPath, false)
                    .setForceReDownload(true)
                    .setListener(mDownloadListener)
                    .start();
        }
    }

    private final FileDownloadListener mDownloadListener = new FileDownloadSampleListener() {

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            mProgressbar.setMax(totalBytes);
            mProgressbar.setProgress(soFarBytes);
            if (mProgressbar.getVisibility() != View.VISIBLE) {
                mProgressbar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            String savePath = task.getTargetFilePath();
            checkAndInstall(savePath);
            mUpdateTextView.setEnabled(true);
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            mUpdateTextView.setEnabled(true);
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            mUpdateTextView.setEnabled(true);
        }
    };

    private void checkAndInstall(String apkPath) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //android 8.0检测未知来源app（判断是否允许安装未知来源app）
            if (AppUtils.canInstallApk()) {
                installApk(apkPath);
            } else {  //未经过允许，则跳转设置，并打开
                mListener.onStartUnknownAppSourceSetting();
            }
        } else {
            installApk(apkPath);
        }
    }

    /*调用系统安装apk并退出app*/
    public void installApk(String apkPath) { //data/user/0/com.holike.crm/files/apk/1.9.4_higher_CRM.apk
        AppUtils.installApp(apkPath);
        dismiss();
        MyApplication.getInstance().exit();
    }

    @Override
    public void dismiss() {
        FileDownloader.getImpl().pause(mDownloadListener);
        super.dismiss();
    }

    @Override
    public Drawable getBackgroundDrawable() {
        return ContextCompat.getDrawable(mContext, R.drawable.bg_corners_white_5dp);
    }

    private static class TipsAdapter extends CommonAdapter<String> {

        TipsAdapter(Context context, List<String> mDatas) {
            super(context, mDatas);
        }

        @Override
        protected int bindView(int viewType) {
            return R.layout.item_version_update;
        }

        @Override
        public void onBindHolder(RecyclerHolder holder, String content, int position) {
            holder.setText(R.id.tv_tips, content);
        }
    }

    public interface OnUpdateListener {
        void onStartUnknownAppSourceSetting();
    }
}
